package com.example.food.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.food.adapter.FoodclassiAdapter;
import com.example.food.adapter.NearAdapter;
import com.example.food.adapter.RecommenFoodAdapter;
import com.example.food.adapter.RotationAdapter;
import com.example.food.adapter.TakeoutSearchAdapter;
import com.example.food.bean.FoodClassBean;
import com.example.food.bean.GpsBean;
import com.example.food.bean.NearBean;
import com.example.food.bean.RecommenFoodBean;
import com.example.food.bean.RotationBean;
import com.example.food.bean.TakeoutSearchBen;
import com.example.home.R;
import com.example.home.tool.OKHttpTool;

import java.util.ArrayList;
import java.util.List;


public class HomePageFragment extends Fragment {
    private ImageView back;
    private TextView adress;
    private SearchView sear;
    private ViewPager vpBanner;
    private RecyclerView rcvHot;
    private RecyclerView rcv_food;
    private RecyclerView rcvList;
    private RecyclerView rcv_search;
    private View view;
    private LinearLayout seed;
    private HPBroadcastReceiver hpBroadcastReceiver;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_page, container, false);
        initView();

        getAddress();
        
        getBanner();

        //美食分类
        foodclassification();

        //推荐好店
        recommendedgood();

        //显示附近商家模块
        nearbybusiness();
        hpBroadcastReceiver = new HPBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("bov_action5");
        HomePageFragment.this.getActivity().registerReceiver(hpBroadcastReceiver,filter);
        return view;
    }

    private void nearbybusiness() {
        OKHttpTool.doNetRequest("prod-api/api/takeout/seller/near",
                OKHttpTool.GET,
                NearBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        NearBean nearBean = (NearBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                NearAdapter nearAdapter = new NearAdapter(getContext(),nearBean.getRows());
                                rcvList.setAdapter(nearAdapter);
                                rcvList.setLayoutManager(new LinearLayoutManager(getContext()));
                                //搜索商家
                                searchforbusiness(nearBean, nearAdapter);
                            }
                        });
                    }
                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void searchforbusiness(NearBean nearBean, NearAdapter nearAdapter) {
        sear.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                seed.setVisibility(View.GONE);
                rcvList.setVisibility(View.GONE);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                rcvList.setVisibility(View.VISIBLE);
                seed.setVisibility(View.VISIBLE);
                rcv_search.setVisibility(View.GONE);
                if (TextUtils.isEmpty(newText)){
                    nearAdapter.setList(nearBean.getRows());
                }else {
                    List<NearBean.RowsBean> list = new ArrayList<>();
                    for (NearBean.RowsBean row : nearBean.getRows()) {
                        if (row.getName().toLowerCase().contains(newText.toLowerCase())){
                            list.add(row);
                        }
                    }
                    nearAdapter.setList(list);
                }
                nearAdapter.notifyDataSetChanged();
                if (!TextUtils.isEmpty(newText)){
                    searchResult(newText);
                }
                return true;
            }
        });
    }

    private void searchResult(String newText) {
        rcv_search.setVisibility(View.VISIBLE);
        OKHttpTool.doNetRequest("prod-api/api/takeout/search?keyword="+newText,
                OKHttpTool.GET,
                TakeoutSearchBen.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        TakeoutSearchBen takeoutSearchBen = (TakeoutSearchBen) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rcv_search.setAdapter(new TakeoutSearchAdapter(getContext(),takeoutSearchBen.getRows()));
                                rcv_search.setLayoutManager(new LinearLayoutManager(getContext()));
                            }
                        });
                    }
                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void recommendedgood() {
        OKHttpTool.doNetRequest("prod-api/api/takeout/seller/list?recommend=Y",
            OKHttpTool.GET,
            RecommenFoodBean.class,
            new OKHttpTool.NetCallback() {
                @Override
                public void onSuccess(Object obj) {
                    RecommenFoodBean recommenFoodBean = (RecommenFoodBean) obj;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            rcvHot.setAdapter(new RecommenFoodAdapter(getContext(),recommenFoodBean.getRows()));
                            rcvHot.setLayoutManager(new GridLayoutManager(getContext(),2));
                        }
                    });
                }
                @Override
                public void onFailure(String msg) {

                }
            });
    }

    private void foodclassification() {
        OKHttpTool.doNetRequest("prod-api/api/takeout/theme/list",
                OKHttpTool.GET,
                FoodClassBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        FoodClassBean foodClassBean = (FoodClassBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rcv_food.setAdapter(new FoodclassiAdapter(getContext(),foodClassBean.getData()));
                                rcv_food.setLayoutManager(new GridLayoutManager(getContext(),1,GridLayoutManager.HORIZONTAL,false));
                            }
                        });
                    }
                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void getBanner() {
        OKHttpTool.doNetRequest("prod-api/api/takeout/rotation/list",
                OKHttpTool.GET,
                RotationBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        RotationBean rotationBean = (RotationBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                RotationAdapter rotationAdapter = new RotationAdapter(HomePageFragment.this.getContext(), rotationBean.getRows());
                                vpBanner.setAdapter(rotationAdapter);
                                    mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
                            }
                        });
                    }
                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                int index = vpBanner.getCurrentItem();
                index = (index + 1) % 3;
                vpBanner.setCurrentItem(index);
                mHandler.sendEmptyMessageDelayed(0, 3 * 1000);
            }
        }
    };

    private void getAddress() {
        OKHttpTool.doNetRequest("prod-api/api/common/gps/location",
                OKHttpTool.GET,
                GpsBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        GpsBean gpsBean = (GpsBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adress.setText(gpsBean.getData().getCity()+"  "+gpsBean.getData().getLocation());
                            }
                        });
                    }


                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void initView() {

        back = view.findViewById(R.id.back);
        adress = view.findViewById(R.id.adress);
        sear = view.findViewById(R.id.sear);
        vpBanner = view.findViewById(R.id.vp_banner);
        rcvHot = view.findViewById(R.id.rcv_hot);
        rcvList = view.findViewById(R.id.rcv_list);
        rcv_food = view.findViewById(R.id.rcv_food);
        seed = view.findViewById(R.id.seed);
        rcv_search = view.findViewById(R.id.rcv_search);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        HomePageFragment.this.getActivity().unregisterReceiver(hpBroadcastReceiver);
    }

    public class HPBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            onResume();
        }
    }
}